package com.feidian.helper.net;

/**
 * net单例
 * @ClassName NetManager
 * @author 林兴强
 * @date 2015.9.29 23:00
 * 
 * */
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class NetManager {
	private static HttpClient client = new DefaultHttpClient();
	private String name;

	private NetManager() {
	}

	private static class NetManagerHolder {
		private static final NetManager INS = new NetManager();
	}

	public static final NetManager getNetManager() {
		return NetManagerHolder.INS;
	}

	/**
	 * Post方法
	 */
	public String getWebWithPost(String url, List<NameValuePair> params) {

		try {
			HttpPost httpRequest = new HttpPost(url);
			for (int i = 0; i < params.size(); i++) {
				if (params.get(i).getValue() != null)
					httpRequest.setEntity(new StringEntity(params.get(i)
							.getValue(), HTTP.UTF_8));
			}
			if (params != null) {
				httpRequest.setEntity(new UrlEncodedFormEntity(params,
						HTTP.UTF_8));
				HttpResponse httpResponse = client.execute(httpRequest);
				if (httpResponse.getStatusLine().getStatusCode() == 200) { // 返回值正常是200
					// COOKIE =
					// ((AbstractHttpClient)client).getCookieStore().getCookies();
					Log.e("httpResponse.getStatusLine().getStatusCode() == 200",
							"httpResponse.getStatusLine().getStatusCode() == 200");
					return readFromStream(httpResponse.getEntity().getContent());
				} else {
					Log.e("httpResponse.getStatusLine().getStatusCode()=",
							httpResponse.getStatusLine().getStatusCode() + "");
					return "-1";
				}
			}
			else{
				Log.e("params_getWebWithPost=null",">>>>>>>>>>>>>>>");
				return "-1";
			}

		} catch (Exception e) {
			Log.e("return null", ">>>>>>>>>>>>>>");
			e.printStackTrace();
		}

		return null;
	}

	public static String readFromStream(InputStream inputStream)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				inputStream, HTTP.UTF_8));
		String data = null;
		while ((data = br.readLine()) != null) {
			sb.append(data);
			Log.e("data=", data);
		}
		if (sb.toString() == null) {
			Log.e("sb.toString()=", null);
		} else {
			Log.e("sb.toString()=", sb.toString());
		}
		return sb.toString();
	}

	/**
	 * 上传文件到服务器类
	 * 
	 * @author tom
	 */
	private static final String TAG = "uploadFile";

	private static final int TIME_OUT = 10 * 1000; // 超时时间

	private static final String CHARSET = "utf-8"; // 设置编码

	public static final String SUCCESS = "1";
	public static final String FAILURE = "0";

	/**
	 * Android上传文件到服务端
	 * 
	 * @param file
	 *            需要上传的文件
	 * @param RequestURL
	 *            请求的rul
	 * @return 返回响应的内容
	 */

	public static String uploadFile(File file, String RequestURL) {
		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
		String PREFIX = "--", LINE_END = "\r\n";
		String CONTENT_TYPE = "multipart/form-data"; // 内容类型
		String context = FAILURE;
		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET);
			// 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
					+ BOUNDARY);
			if (file != null) {
				/** * 当文件不为空，把文件包装并且上传 */
				OutputStream outputSteam = conn.getOutputStream();
				DataOutputStream dos = new DataOutputStream(outputSteam);
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				/**
				 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字，包含后缀名的 比如:abc.png
				 */
				sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
						+ file.getName() + "\"" + LINE_END);
				sb.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINE_END);
				sb.append(LINE_END);
				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = is.read(bytes)) != -1) {
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
						.getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功 当响应成功，获取响应的流
				 */
				int res = conn.getResponseCode();
				Log.e(TAG, "response code:" + res);
				try {
					Log.e("my test", ".........");
					context = readFromStream(conn.getInputStream());
					Log.e("content=", readFromStream(conn.getInputStream()));
					Log.e("content=", conn.getContent().toString());
					Log.e("my test", ".........");
				} catch (Exception e) {
					e.printStackTrace();
				}

				if (res == 200) {
					return context;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return FAILURE;
	}

	public static Bitmap getBitmap(String u) {
		Bitmap bitmap = null;
		try {
			URL url = new URL(u);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.connect();
			bitmap = BitmapFactory.decodeStream(conn.getInputStream());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}

}
